package com.leon.raw_provider.tool;

import com.leon.rpc.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.stream.Stream;

public class UserServiceHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest)msg;

        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        Object bean = ApplicationContextHelper.getBean(aClass);
        if (bean != null) {
            // 通过反射执行方法调用
            Class<?> beanClass = bean.getClass();
            Method method = beanClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());

            Object result = method.invoke(bean, rpcRequest.getParameters());

            Stream.of(rpcRequest.getParameters()).forEach(obj -> System.out.println(obj.toString()));

            // 返回值封装到 rpcRequest 对象中
            rpcRequest.setResult(result);
            ctx.writeAndFlush(rpcRequest);
        }
    }
}
